﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ResearchRepository.Models;

namespace ResearchRepository
{
    public partial class RRNewProject : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
			 // if not logged in, then redirect to login page
            if (Session[GLOBALS.userObjSessionVar] == null)
            {
                Response.Redirect("Login.aspx");
            }
            populateDisciplineList();
        }

        protected void submitProjectButton_Click(object sender, EventArgs e)
        {
            // Create request
            RRUser u = (RRUser)Session[GLOBALS.userObjSessionVar];
            RRRequest request = new RRRequest();
            RRPermissionType perm = RRPermissionType.None;
            request.ReqType = RRRequestType.NewProj;
            request.UserID = u.UserID;
            request.Note = projectNotesBox.Text;

            request.NewProjName = projectNameBox.Text;
            request.DiscID = int.Parse(disciplineList.SelectedValue);

            // Set default privacy level
            if (privacyList.SelectedIndex == 1)
            {
                perm = RRPermissionType.View;
            }
            else if (privacyList.SelectedIndex == 2)
            {
                perm = RRPermissionType.Read;
            }
            else if (privacyList.SelectedIndex == 3)
            {
                perm = RRPermissionType.Write;
            }
            else if (privacyList.SelectedIndex == 4)
            {
                perm = RRPermissionType.Admin;
            }

			request.PermType = perm;

            // Submit request
            try
            {
                RRDatabaseManager.createRequest(request);
                successDiv.Visible = true;
                newProjectTable.Visible = false;
            }
            catch (Exception x)
            {
                //TODO?? handle?
                failureDiv.Visible = true;
            }
        }
		
		//TODO: use a TreeView to display the hierarchy of disciplines formed by recursive relation in DB
        protected void populateDisciplineList()
        {
            var disciplines = RRDatabaseManager.getDisciplineList();

            disciplineList.DataSource = disciplines;
            disciplineList.DataTextField = "DiscName";
            disciplineList.DataValueField = "DiscId";
            disciplineList.DataBind();
        }
    }
}